<template>
  <div class="website-traffic">
    <el-card class="traffic-card" :body-style="{ padding: '0' }">
      <div class="card-header">
        <h3 class="title">网站流量分析</h3>
        <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="custom-tabs">
          <el-tab-pane label="流量趋势" name="daily">
            <div class="chart-container" ref="dailyChart"></div>
          </el-tab-pane>
          <el-tab-pane label="月访问量" name="monthly">
            <div class="chart-container" ref="monthlyChart"></div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDailyTraffic, getMonthlyTraffic } from '@/api/dashboard/traffic'

export default {
  name: 'WebsiteTraffic',
  data() {
    return {
      activeTab: 'daily',
      dailyChart: null,
      monthlyChart: null,
      dailyData: {
        times: [],
        totalVisits: [],
        uniqueVisitors: []
      },
      monthlyData: {
        months: [],
        visits: []
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.dailyChart?.dispose()
    this.monthlyChart?.dispose()
  },
  methods: {
    // 获取图表数据
    async fetchData() {
      try {
        // 获取日流量数据
        const dailyRes = await getDailyTraffic()
        if (dailyRes.data) {
          // 数据对齐处理，确保 times、totalVisits、uniqueVisitors 长度一致且一一对应
          const times = dailyRes.data.times || []
          const totalVisits = (dailyRes.data.totalVisits || []).slice(0, times.length).map(v => Number(v) || 0)
          const uniqueVisitors = (dailyRes.data.uniqueVisitors || []).slice(0, times.length).map(v => Number(v) || 0)
          this.dailyData = { times, totalVisits, uniqueVisitors }
        }
    
        // 获取月访问量数据
        const monthlyRes = await getMonthlyTraffic()
        if (monthlyRes.data) {
          this.monthlyData = monthlyRes.data
        }
    
        // 只初始化当前激活 tab 的图表
        this.$nextTick(() => {
          if (this.activeTab === 'daily') {
            this.initDailyChart()
          } else {
            this.initMonthlyChart()
          }
        })
        window.addEventListener('resize', this.handleResize)
      } catch (error) {
        console.error('获取流量数据失败:', error)
      }
    },
    // 切换 tab 时只初始化/resize 当前 tab 的图表
    handleTabClick(tab) {
      // 切换 tab 时只初始化/resize 当前 tab 的图表
      this.$nextTick(() => {
        if (this.activeTab === 'daily') {
          this.initDailyChart()
        } else {
          this.initMonthlyChart()
        }
      })
    },
    // 初始化日流量图表
    initDailyChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.dailyChart
        if (!chartDom) return
        if (this.dailyChart) {
          this.dailyChart.dispose()
        }
        this.dailyChart = echarts.init(chartDom)
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: 'rgba(51, 112, 255, 0.1)'
              }
            },
            backgroundColor: '#fff',
            borderWidth: 0,
            padding: [12, 16],
            textStyle: {
              color: '#1f2329',
              fontSize: 13
            },
            formatter: function(params) {
              let time = params[0].axisValue;
              let html = `<div style="font-weight:500;color:#1f2329;margin-bottom:8px;">${time}</div>`;
              params.forEach(item => {
                html += `<div style="display:flex;align-items:center;margin:4px 0;">
                  <span style="display:inline-block;margin-right:8px;width:8px;height:8px;border-radius:50%;background:${item.color};"></span>
                  <span style="color:#646a73;">${item.seriesName}：</span>
                  <span style="color:#1f2329;font-weight:500;margin-left:4px;">${item.value.toLocaleString()}</span>
                </div>`;
              });
              return html;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '6%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.dailyData.times || [],
            axisLine: {
              lineStyle: {
                color: '#e5e6eb'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#646a73',
              fontSize: 12
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#e5e6eb',
                type: 'dashed'
              }
            }
          },
          yAxis: {
            type: 'value',
            splitLine: {
              lineStyle: {
                color: '#e5e6eb',
                type: 'dashed'
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#646a73',
              fontSize: 12,
              formatter: function(value) {
                return value === 0 ? '' : value.toLocaleString()
              }
            }
          },
          series: [
            {
              name: '总访问量',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              showSymbol: false,
              lineStyle: {
                width: 3,
                color: '#3370ff'
              },
              areaStyle: {
                opacity: 0.1,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(51, 112, 255, 0.2)' },
                  { offset: 1, color: 'rgba(51, 112, 255, 0.05)' }
                ])
              },
              emphasis: {
                focus: 'series',
                scale: true
              },
              data: this.dailyData.totalVisits || [],
              animationDuration: 1000,
              animationEasing: 'cubicOut'
            },
            {
              name: '独立访客',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              showSymbol: false,
              lineStyle: {
                width: 3,
                color: '#00b42a'
              },
              areaStyle: {
                opacity: 0.1,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(0, 180, 42, 0.2)' },
                  { offset: 1, color: 'rgba(0, 180, 42, 0.05)' }
                ])
              },
              emphasis: {
                focus: 'series',
                scale: true
              },
              data: this.dailyData.uniqueVisitors || [],
              animationDuration: 1000,
              animationEasing: 'cubicOut'
            }
          ]
        }
        this.dailyChart.setOption(option)
        setTimeout(() => { this.dailyChart && this.dailyChart.resize() }, 0)
        setTimeout(() => { this.dailyChart && this.dailyChart.resize() }, 300)
      })
    },
    // 初始化月访问量图表
    initMonthlyChart() {
      this.$nextTick(() => {
        const chartDom = this.$refs.monthlyChart
        if (!chartDom) return
        if (this.monthlyChart) {
          this.monthlyChart.dispose()
        }
        this.monthlyChart = echarts.init(chartDom)
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: '#fff',
            borderWidth: 0,
            padding: [12, 16],
            textStyle: {
              color: '#1f2329',
              fontSize: 13
            },
            formatter: function(params) {
              let month = params[0].axisValue;
              let html = `<div style="font-weight:500;color:#1f2329;margin-bottom:8px;">${month}</div>`;
              params.forEach(item => {
                html += `<div style="display:flex;align-items:center;margin:4px 0;">
                  <span style="display:inline-block;margin-right:8px;width:8px;height:8px;border-radius:50%;background:${item.color};"></span>
                  <span style="color:#646a73;">访问量：</span>
                  <span style="color:#1f2329;font-weight:500;margin-left:4px;">${item.value.toLocaleString()}</span>
                </div>`;
              });
              return html;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '6%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.monthlyData.months || [],
            axisLine: {
              lineStyle: {
                color: '#e5e6eb'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#646a73',
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value',
            splitLine: {
              lineStyle: {
                color: '#e5e6eb',
                type: 'dashed'
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#646a73',
              fontSize: 12,
              formatter: function(value) {
                return value === 0 ? '' : value.toLocaleString()
              }
            }
          },
          series: [
            {
              name: '访问量',
              type: 'bar',
              data: this.monthlyData.visits || [],
              barWidth: '40%',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#3370ff' },
                  { offset: 1, color: '#3370ff' }
                ]),
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#2860e1' },
                    { offset: 1, color: '#2860e1' }
                  ])
                }
              },
              animation: true,
              animationDuration: 2000,
              animationEasing: 'elasticOut',
              animationDelay: function (idx) {
                return idx * 150;
              },
              animationDurationUpdate: 1000,
              animationEasingUpdate: 'quinticInOut'
            }
          ],
          animationDuration: 2000,
          animationEasing: 'elasticOut',
          animationDelayUpdate: function (idx) {
            return idx * 150;
          }
        }
        this.monthlyChart.setOption(option)
        setTimeout(() => { this.monthlyChart && this.monthlyChart.resize() }, 0)
        setTimeout(() => { this.monthlyChart && this.monthlyChart.resize() }, 300)
      })
    },
    // 监听窗口大小变化
    handleResize() {
      this.dailyChart?.resize()
      this.monthlyChart?.resize()
    }
  }
}
</script>

<style lang="scss" scoped>
.website-traffic {
  .traffic-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
  }

  .card-header {
    padding: 20px 24px 0;

    .title {
      margin: 0 0 16px;
      font-size: 16px;
      font-weight: 500;
      color: #1f2329;
    }
  }

  .custom-tabs {
    :deep(.el-tabs__nav-wrap::after) {
      height: 1px;
      background: #e5e6eb;
    }

    :deep(.el-tabs__item) {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      color: #646a73;
      transition: all 0.3s ease;

      &.is-active {
        color: #3370ff;
        font-weight: 500;
      }

      &:hover {
        color: #3370ff;
      }
    }
  }

  .chart-container {
    height: 400px;
    padding: 20px 24px;
  }
}
</style>